package com.leef.glidetest.glide;

import android.content.Context;

import com.bumptech.glide.load.data.DataFetcher;
import com.bumptech.glide.load.model.GenericLoaderFactory;
import com.bumptech.glide.load.model.ModelCache;
import com.bumptech.glide.load.model.ModelLoader;
import com.bumptech.glide.load.model.ModelLoaderFactory;
import com.leef.glidetest.bean.SecretData;

import java.io.InputStream;

/**
 * Created by IWALL on 2016/3/18.
 * model loader
 */
public class SecretModelLoader implements ModelLoader<SecretData, InputStream> {

    private final ModelCache<SecretData, SecretData> cache;

    public SecretModelLoader() {
        this(null);
    }

    public SecretModelLoader(ModelCache<SecretData, SecretData> cache) {
        this.cache = cache;
    }

    @Override
    public DataFetcher<InputStream> getResourceFetcher(SecretData model, int width, int height) {
        SecretData data = model;
        if (cache != null) {
            //  如果图片存在缓存 --> 1
            data = cache.get(model, 0, 0);
            //  如果图片不存在缓存 --> 2
            if (data == null) {
                // 2 将图片放入缓存
                cache.put(model, 0, 0, model);
                return new SecretDataFetcher(model);
            }
        }
        //  1
        return new SecretDataFetcher(data);
    }

    public static class Factory implements ModelLoaderFactory<SecretData, InputStream> {

        private final ModelCache<SecretData, SecretData> cache = new ModelCache<>(500);

        @Override
        public ModelLoader<SecretData, InputStream> build(Context context, GenericLoaderFactory factories) {
            return new SecretModelLoader(cache);
        }

        @Override
        public void teardown() {

        }
    }
}
